package com.sptpc.hello.controller;

import com.sptpc.hello.controller.requests.ModifyCategoryRequest;
import com.sptpc.hello.modei.Category;
import com.sptpc.hello.modei.Drink;
import com.sptpc.hello.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/category/")
public class CategoryController {
    @Autowired
    public ICategoryService categoryService;

    @GetMapping("/")
    public List<Category> getAll(){
        List<Category> results = categoryService.getAllCategories();
        return results;
    }


    @PostMapping("/")
    public Category addNewCategory(@RequestBody @Valid Category category,
                                          BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            for (ObjectError error : bindingResult.getAllErrors()) {
                log.error(error.toString());
            }
            return null;
        }else{
            log.info("创建新的分类：{}", category);
            categoryService.addNewCategory(category);
            return category;
        }

    }
    // put /category/
    @PutMapping("/")
    public Category modifyDrink(@RequestBody ModifyCategoryRequest request) {
        log.info("要修改的饮品分类:{}", request);
//        Drink updatedrink = Drink.builder().id(1).name("茉莉花茶").price(Money.parse("USD 23.87")).build();
        //通过id查找出饮品
        Category category = categoryService.getCategoryById(request.getId());
        BeanUtils.copyProperties(request,category);
        categoryService.updateCategory(category);

        return category;
    }

    @DeleteMapping("/{id}")
    public String deleteCategory(@PathVariable Integer id) {
         log.info("要删除的饮品分类id:{}", id);
         categoryService.deleteCategoryById(id);
         return "删除成功";
    }


}
